<?php
    /**
     * Created by PhpStorm.
     * User: huangzhongwei
     * Date: 2018/10/23
     * Time: 11:27
     */

    namespace app\api\service;

    use app\api\service\JuheSms;
    use app\lib\exception\SmsException;
    use app\lib\exception\MissException;

    class Account
    {


        /**
         * 发送验证码
         *
         * @param $telephone
         *
         * @return bool
         * @throws SmsException
         */
        public function sendVerificationCode($telephone)
        {
            //验证码 缓存时间
            $interval = config('setting.sms_cache_time');
            //生成验证码
            $num     = rand(100000, 999999);
            $smsConf = [
                'key'       => config('setting.sms_juhe_key'), //您申请的APPKEY
                'mobile'    => $telephone, //接受短信的用户手机号码
                'tpl_id'    => config('setting.sms_tpl_id'), //您申请的短信模板ID，根据实际情况修改
                'tpl_value' => "#code#={$num}&#m#=5" //您设置的模板变量，根据实际情况修改
            ];
            cache($telephone, ['captcha' => $num], 300);
            $content = JuheSms::juhecurl($smsConf, 1);
            if ($content) {
                $result     = json_decode($content, true);
                $error_code = $result['error_code'];
                if ($error_code == 0) {
                    //状态为0，说明短信发送成功
                    return true;
                } else {
                    //状态非0，说明失败
                    throw new SmsException(['msg' => '短信发送失败,' . $result['reason']]);
                }
            } else {
                //返回内容异常，以下可根据业务逻辑自行修改
                throw new SmsException(['msg' => '短信发送失败']);
            }
        }

        /**
         * 检测验证码
         * @param $telephone
         * @param $captcha
         *
         * @return bool
         */
        public function checkCaptcha($telephone, $captcha)
        {
            $cacheCaptcha = cache($telephone);
            if ($cacheCaptcha['captcha'] != $captcha) {
                throw new MissException(['msg' => '验证码错误', 'errorCode' => '10001']);
            }
            return true;
        }

    }